//---------------------------------------------------------------------
// Authors: AlexAngelopoulos, Keith Hill, jachymko
//
// Description: Class implementing New-HardLink command.
//
// Creation Date: Oct  9, 2006
// Modified Date: Dec 13, 2006
//
//---------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.IO;
using System.Management.Automation;

namespace Pscx.Commands.FileSystem.Ntfs
{
    using Interop;

    [Cmdlet(VerbsCommon.New, PscxNouns.Hardlink)]
    [Description("Creates filesystem hard links. The hardlink and the target must reside on the same NTFS volume.")]
    public partial class NewHardLinkCommand : NewLinkCommandBase
    {
        protected override void ProcessRecord()
        {
            if (!File.Exists(FullTarget))
            {
                // The target file for the hard link doesn't exist.
                WriteError(PscxErrorRecord.FileNotFoundError(Target));
                return;
            }

            // removed the unnecessary and broken path root comparison. CreateHardLink will check it correctly.
            // imagine you had volume X:\ mounted also as C:\Volumes\X. the GetPathRoot way 
            // would refuse to link C:\Volumes\X\blabla to X:\other\blabla, which it's perfectly
            // legal

            if (!NativeMethods.CreateHardLink(FullPath, FullTarget, IntPtr.Zero))
            {
                WriteError(PscxErrorRecord.LastWin32Error("CreateHardLinkError", ErrorCategory.NotSpecified, Path));
                return;
            }

            WriteObject(new FileInfo(FullPath));
        }

    }
}
